package com.chang.controller;

import com.chang.entity.Admin;
import com.chang.entity.Essay;
import com.chang.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.List;
import  org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.util.UUID;

@Controller
public class AdminController {

    @Autowired
    private AdminService adminService;

    private Admin currentAdmin;
    private Admin currentUser;

    @RequestMapping("/add")
    public ModelAndView add(@RequestParam(value = "uploadavatar",required = false)MultipartFile file,
                    String username,String phone,
                    String sex,String birthday,String introduction,HttpServletRequest request)throws Exception {
        ModelAndView mv = new ModelAndView("admin_info");

        System.out.println(request.getServletContext().getRealPath("/upload"));

        currentAdmin.setAdmin_name(username);
        currentAdmin.setAdmin_phone(phone);
        currentAdmin.setAdmin_born(birthday);
        currentAdmin.setAdmin_brief(introduction);
        currentAdmin.setAdmin_sex(sex);

        //添加传入图片的地址
        String filePath = "D:\\upload"; //定义图片上传后的路径
        String alies = "upload";//tomcat设置的别名
        String newFileName = "/" + alies + "/" + fileOperate(file,filePath);
        currentAdmin.setAdmin_image(newFileName);
        adminService.updateAdmin(currentAdmin);

        mv.addObject("msg","操作成功！");
        return mv;
    }

    private String fileOperate(MultipartFile file,String filePath) {

        String originalFileName = file.getOriginalFilename();//获取原始图片的扩展名
        System.out.println("图片原始名称："+originalFileName);
        String newFileName = UUID.randomUUID()+originalFileName;  //新的文件名称
        System.out.println("新的文件名称："+newFileName);
        File targetFile = new File(filePath,newFileName); //创建新文件
        try {
            file.transferTo(targetFile); //把本地文件上传到文件位置 , transferTo()是springmvc封装的方法，用于图片上传时，把内存中图片写入磁盘
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return newFileName;
    }


    /**
     * 登录方法
     * @param username 输入的用户名
     * @param password 输入的密码
     *  成功到title，否则返回上一页面
     */
    @RequestMapping("/login")
    public void check( HttpSession session,HttpServletResponse response,String username, String password) throws IOException {
        //控制台输出，方便查看
        System.out.println(username +"---" +password);

        response.setContentType("text/html;charset=utf-8");
        //ModelAndView mv = new ModelAndView();

        /*在管理员表中检索*/
        this.currentAdmin = adminService.checkAdmin(username,password);

        /*检索到信息，则登录成功*/
        if(currentAdmin != null){
            /*测试用*/
            System.out.println("以管理员身份登上了");
            /*将管理员对象设置到session中，在页面中可以访问到*/
            session.setAttribute("currentUser",currentAdmin);
            /*同时设置一个是否为管理员的标识，管理员为true，非管理员为null*/
            session.setAttribute("isAdmin",true);
            response.sendRedirect("myIndex");
            //mv.setViewName("title");
        }else{
            /*否则在用户表中检索*/
            this.currentUser = adminService.checkUser(username,password);
            /*用户表中检索到信息*/
            if(currentUser != null){
                /*测试用*/
                System.out.println("以用户身份登上了");
                /*将用户对象设置到session中*/
                session.setAttribute("currentUser",currentUser);
                response.getWriter().print("<script type='text/javascript'>alert('登录成功！');");
                //mv.setViewName("title");
                //return mv;
                response.sendRedirect("myIndex");
                return;
            }
            /*管理员表和用户表中都没有相应信息，返回同名ModelAndView和错误信息*/
            response.getWriter().print("<script type='text/javascript'>alert('用户名或密码错误！');window.history.go(-1)</script>");
            //mv.addObject("msg","用户名或密码错误");
            System.out.println("没登上。。。");
        }
        //return mv;
    }

    /**
     * 管理员注册方法
     * @param username 用户名
     * @param password 密码
     * @param phone 电话
     */
    @RequestMapping("/resign")
    public void insertAdmin(HttpServletResponse response,HttpSession session,String username,String password,String phone) throws IOException {
        //ModelAndView mv = new ModelAndView();
        response.setContentType("text/html;charset=utf-8");
        /*注册前的检查*/
        Admin tempAdmin = adminService.checkAdminByName(username);
        /*不为null说明已经有数据，返回同名登录页面并提示错误信息*/
        if(tempAdmin != null){
            /*在页面中以提示框形式输出提示信息*/
            response.getWriter().print("<script type='text/javascript'>alert('用户名已存在！');window.history.go(-1)</script>");
            return;
        }

        int result = adminService.insertAdmin(username,password,phone);
        /*测试用*/
        System.out.println(username+"===="+password+"===="+result);
        if(result != 0){
            this.currentAdmin = adminService.checkAdmin(username,password);
            /*将管理员对象设置到session中*/
            session.setAttribute("currentUser",currentAdmin);
            /*在页面中以提示框形式输出提示信息*/
            response.getWriter().print("<script type='text/javascript'>alert('注册成功！')</script>");
            //mv.setViewName("title");
            response.sendRedirect("title");
        }else{
            response.getWriter().print("<script type='text/javascript'>alert('注册失败！');window.history.go(-1)</script>");
        }
        //return mv;
    }
    //用户注册方法
    @RequestMapping("/")
    public void insertUser(HttpServletResponse response,HttpSession session,String username,String password,String phone) throws IOException {
        response.setContentType("text/html;charset=utf-8");
        //ModelAndView mv = new ModelAndView();

        /*注册前先检查是否有同名数据*/
        Admin tempAdmin = adminService.checkUserByName(username);
        /*不为null说明已经有数据，返回同名登录页面并提示错误信息*/
        if(tempAdmin != null){
            /*在页面中以提示框形式输出提示信息*/
            response.getWriter().print("<script type='text/javascript'>alert('用户名已存在！');window.history.go(-1)</script>");
            return;
        }

        int result = adminService.insertUser(username,password,phone);
        /*测试用*/
        System.out.println(username+"===="+password+"===="+result);
        if(result != 0){
            this.currentUser = adminService.checkUser(username,password);
            /*将用户对象设置到session中*/
            session.setAttribute("currentUser",currentUser);
            response.getWriter().print("<script type='text/javascript'>alert('注册成功！')</script>");
            /*登录成功，转到登录后的title页面*/
            //mv.setViewName("title");
            response.sendRedirect("title");
        }else{
            response.getWriter().print("<script type='text/javascript'>alert('注册失败！');window.history.go(-1)</script>");
        }
        //return mv;
    }

    @RequestMapping("/getImg")
    public void getImg(Integer id,HttpServletResponse response){
        try{
            Admin admin = adminService.checkAdminById(id);
            byte[] byteArr = (byte[])admin.getAdmin_image();
            String data = new String(byteArr,"UTF-8");
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] bytes = decoder.decodeBuffer(data);
            for(byte i:bytes){
                if(i < 0){
                    i+=256;
                }
            }
            response.setContentType("image/png");
            ServletOutputStream out = response.getOutputStream();
            out.write(bytes);
            out.flush();
            out.close();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 管理员更改基本信息
     * @param username
     * @param phone
     * @param sex
     * @param birthday
     * @param introduction
     * @param file
     * @return
     * @throws IOException
     */
    @RequestMapping("/updateAdminBasicInfo")
    public ModelAndView updateAdminBasicInfo(String username,
                                             String phone,
                                             String sex,
                                             String birthday,
                                             String introduction,
            @RequestParam(value = "uploadavatar",required = false)MultipartFile file) throws IOException {
        ModelAndView mv = new ModelAndView("admin_info");

        if(!file.isEmpty()){//文件为空的检测
            if(file.getSize() >= 1024*1024*2){//文件大小检测
                mv.addObject("msg","请上传小于2M的图片！");
                return mv;
            }
            BASE64Encoder encoder = new BASE64Encoder();
            //文件转换为byte，再用BASE64编码转换
            String img = encoder.encode(file.getBytes());
            this.currentAdmin.setAdmin_image(img);
        }

        int result;

        this.currentAdmin.setAdmin_name(username);
        this.currentAdmin.setAdmin_phone(phone);
        this.currentAdmin.setAdmin_sex(sex);
        this.currentAdmin.setAdmin_born(birthday);
        this.currentAdmin.setAdmin_brief(introduction);

        result = adminService.updateAdmin(this.currentAdmin);

        if(result != 0){
            /*测试用*/
            System.out.println("管理员信息更新成功："+this.currentAdmin.getAdmin_name()+"=="+this.currentAdmin.getAdmin_pas()+"=="+this.currentAdmin.getAdmin_phone());
            /*在页面显示提示信息*/
            mv.addObject("msg","操作成功！");
        }else{
            /*测试用*/
            System.out.println("管理员信息更新失败！");
            mv.addObject("msg","操作失败！");
        }
        return mv;
    }

    /**
     * 管理员更改密码
     * @param password
     * @return
     */
    @RequestMapping("/updateAdminPas")
    public ModelAndView updateAdminPas(String password){
        ModelAndView mv = new ModelAndView("admin_info");
        this.currentAdmin.setAdmin_pas(password);
        int result = adminService.updateAdmin(this.currentAdmin);
        if(result != 0){
            /*测试用*/
            System.out.println("管理员密码更新成功："+this.currentAdmin.getAdmin_name()+"=="+this.currentAdmin.getAdmin_pas()+"=="+this.currentAdmin.getAdmin_phone());
            /*在页面显示提示信息*/
            mv.addObject("msg","操作成功！");
        }else{

            /*测试用*/
            System.out.println("管理密码更新失败！");
            mv.addObject("msg","操作失败！");
        }
        return mv;
    }


    /**
     * 用户更改基本信息
     * @param username
     * @param phone
     * @param sex
     * @param birthday
     * @param introduction
     * @param file
     * @return
     * @throws IOException
     */
    @RequestMapping("/updateUserBasicInfo")
    public ModelAndView updateUserBasicInfo(String username,
                                             String phone,
                                             String sex,
                                             String birthday,
                                             String introduction,
                                             @RequestParam(value = "uploadavatar",required = false)MultipartFile file) throws IOException {
        ModelAndView mv = new ModelAndView("admin_info");

        if(!file.isEmpty()){//文件为空的检测
            if(file.getSize() >= 1024*1024*2){//文件大小检测
                mv.addObject("msg","请上传小于2M的图片！");
                return mv;
            }
            BASE64Encoder encoder = new BASE64Encoder();
            //文件转换为byte，再用BASE64编码转换
            String img = encoder.encode(file.getBytes());
            this.currentUser.setAdmin_image(img);
        }

        int result;

        this.currentUser.setAdmin_name(username);
        this.currentUser.setAdmin_phone(phone);
        this.currentUser.setAdmin_sex(sex);
        this.currentUser.setAdmin_born(birthday);
        this.currentUser.setAdmin_brief(introduction);

        result = adminService.updateAdmin(this.currentUser);

        if(result != 0){
            /*测试用*/
            System.out.println("用户信息更新成功："+this.currentUser.getAdmin_name()+"=="+this.currentUser.getAdmin_pas()+"=="+this.currentUser.getAdmin_phone());
            /*在页面显示提示信息*/
            mv.addObject("msg","操作成功！");
        }else{
            /*测试用*/
            System.out.println("用户信息更新失败！");
            mv.addObject("msg","操作失败！");
        }
        return mv;
    }

    /**
     * 用户更改密码
     * @param password
     * @return
     */
    @RequestMapping("/updateUserPas")
    public ModelAndView updateUserPas(String password){
        ModelAndView mv = new ModelAndView("admin_info");
        this.currentUser.setAdmin_pas(password);
        int result = adminService.updateUser(this.currentUser);
        if(result != 0){
            /*测试用*/
            System.out.println("用户密码更新成功："+this.currentUser.getAdmin_name()+"=="+this.currentUser.getAdmin_pas()+"=="+this.currentUser.getAdmin_phone());
            /*在页面显示提示信息*/
            mv.addObject("msg","操作成功！");
        }else{

            /*测试用*/
            System.out.println("用户密码更新失败！");
            mv.addObject("msg","操作失败！");
        }
        return mv;
    }

    /**
     * 删除，成功删除清除session，清除全局变量currentAdmin/User，并回到首页，否则返回
     * @param response
     * @param session
     * @throws IOException
     */
    @RequestMapping("/deleteAdmin")
    public void deleteAdmin(HttpServletResponse response,HttpSession session) throws IOException {
        response.setContentType("text/html;charset=utf-8");

        /*登录后才能进行删除操作，所以 this.currentAdmin 已经有值*/
        boolean isDelete = adminService.deleteAdmin(this.currentAdmin.getAdmin_Id());

        if(isDelete){
            /*清除session*/
            session.removeAttribute("currentUser");
            this.currentAdmin = null;
            response.getWriter().print("<script type='text/javascript'>alert('操作成功！')");
            response.sendRedirect("index");
        }else {
            response.getWriter().print("<script type='text/javascript'>alert('操作失败！');window.history.go(-1)");
        }
    }
    @RequestMapping("/deleteUser")
    public void deleteUser(HttpServletResponse response,HttpSession session) throws IOException {
        response.setContentType("text/html;charset=utf-8");

        /*登录后才能进行删除操作，所以 this.currentAdmin 已经有值*/
        boolean isDelete = adminService.deleteUser(this.currentUser.getAdmin_Id());

        if(isDelete){
            session.removeAttribute("currentUser");
            this.currentUser = null;
            response.getWriter().print("<script type='text/javascript'>alert('操作成功！')");
            response.sendRedirect("index");
        }else {
            response.getWriter().print("<script type='text/javascript'>alert('操作失败！');window.history.go(-1)");
        }
    }

    //查询所有数据的方法
    @RequestMapping("/findAll")
    public String findAll(HttpServletRequest request) {
        List<Admin> admins = adminService.findAllAdmin();
        List<Admin> users = adminService.findAllUser();
        request.setAttribute("admins", admins);
        request.setAttribute("users", users);
        return "show";
    }

    @RequestMapping("/Count")
    public String Count(HttpServletRequest request) {
        List<Admin> admins = adminService.Count();
        request.setAttribute("admins", admins);
        return "showcount";
    }

    //只查询所有的管理员
    @RequestMapping("onlyFindAllAdmin")
    public String onlyFindAllAdmin(HttpServletRequest request) {
        List<Admin> admins = adminService.findAllAdmin();
        request.setAttribute("admin",admins);
        return "hotLine";
    }

    @RequestMapping("goAdministrator")
    public String goAdministrator() {
        /*目前是管理员和用户都可以进入“我的”这个页面，如有需要，在此进行修改*/
        if(this.currentAdmin != null || this.currentUser != null)
            return "Administrator";
        else
            return "login";
    }
    @RequestMapping("/AllInfo")
    public String AllInfo(HttpServletRequest request) {
        List<Admin> admins = adminService.findAllAdmin();
        List<Admin> users = adminService.findAllUser();
        request.setAttribute("admins", admins);
        request.setAttribute("users", users);
        return "userdata";
    }

    @RequestMapping("goLogin")
    public String goLogin() {
        return "login";
    }



}
